package com.carrental.gateway.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.Collections;
import java.util.Set;

import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_ORIGINAL_REQUEST_URL_ATTR;
import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR;
import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR;

/**
 * 全局日志过滤器
 * 记录所有经过网关的请求和路由信息
 */
@Component
public class LoggingFilter implements GlobalFilter, Ordered {

    private static final Logger LOGGER = LoggerFactory.getLogger(LoggingFilter.class);

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        
        // 获取原始请求路径
        Set<URI> originalUris = exchange.getAttributeOrDefault(GATEWAY_ORIGINAL_REQUEST_URL_ATTR, Collections.emptySet());
        String originalUri = (originalUris.isEmpty()) ? "Unknown" : originalUris.iterator().next().toString();
        
        // 获取目标路由信息
        Route route = exchange.getAttribute(GATEWAY_ROUTE_ATTR);
        URI targetUri = exchange.getAttribute(GATEWAY_REQUEST_URL_ATTR);
        
        // 记录请求信息
        LOGGER.info("=== Gateway Request Info ===");
        LOGGER.info("Method: {}", request.getMethod());
        LOGGER.info("Path: {}", request.getPath());
        LOGGER.info("Original URI: {}", originalUri);
        LOGGER.info("Target URI: {}", targetUri);
        
        if (route != null) {
            LOGGER.info("Route ID: {}", route.getId());
            LOGGER.info("Route URI: {}", route.getUri());
            LOGGER.info("Route Predicates: {}", route.getPredicate());
        }
        
        // 记录请求头信息
        LOGGER.debug("Request Headers: {}", request.getHeaders());
        
        // 继续处理请求，并在响应返回时记录响应信息
        return chain.filter(exchange)
                .then(Mono.fromRunnable(() -> {
                    LOGGER.info("=== Gateway Response Info ===");
                    LOGGER.info("Status Code: {}", exchange.getResponse().getStatusCode());
                    LOGGER.debug("Response Headers: {}", exchange.getResponse().getHeaders());
                }));
    }

    @Override
    public int getOrder() {
        // 设置为最高优先级，确保这个过滤器最先执行
        return Ordered.HIGHEST_PRECEDENCE;
    }
} 